package com.zte.claa.inficombo.csa.app.service.rptparse.ext.gnss.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.config.HCGNSSSvrCommProps;
import com.zte.claa.inficombo.csa.app.service.rptparse.ext.gnss.IGnssParseResultReceiver;

/**
 * 
 * @项目名称 GNSS parse result Receiver Server
 * @类名 MessageAcceptor
 * @类描 异步消息监听器，用于接收GNSS服务器异步发回来的解算结果。

 * @创建时间 2018-8-18
 *
 */
public class GnssParseResultAcceptor {
	private static final Logger LOG = LoggerFactory.getLogger(GnssParseResultAcceptor.class);
	private int processorCount = 1;
	private IoAcceptor acceptor = null;
	// 初始化时设置.
	private HCGNSSSvrCommProps gnssComm = null;
	// 初始化时设置.
	private IGnssParseResultReceiver resultReceiver = null;

	public void setProcessorCount(int processorCount) {
		this.processorCount = processorCount;
	}

	public void setGnssComm(HCGNSSSvrCommProps gnssComm) {
		this.gnssComm = gnssComm;
	}

	public void setResultReceiver(IGnssParseResultReceiver resultReceiver) {
		this.resultReceiver = resultReceiver;
	}

	public void startUp() throws IOException {
		if (null == acceptor) {
			// 实例化监听器并设置处理线程数
			acceptor = new NioSocketAcceptor(processorCount);
			// 服务端编码设
			GnssMsgDecoder decoder = new GnssMsgDecoder(Charset.forName(this.gnssComm.getCharsetname()));
			GnssMsgEncoder encoder = new GnssMsgEncoder(Charset.forName(this.gnssComm.getCharsetname()));
			GnssMsgCodecFactory codecFactory = new GnssMsgCodecFactory(decoder, encoder);
			acceptor.getFilterChain().addLast("logger", new LoggingFilter());
			acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(codecFactory));
			// 设置消息处理器
			acceptor.setHandler(new GnssParseResultIoHandler(this.resultReceiver));
			// 设置接受缓冲区大
			acceptor.getSessionConfig().setReadBufferSize(this.gnssComm.getLocalRecvBufsize());
			// 绑定监听端口
			acceptor.bind(new InetSocketAddress(this.gnssComm.getLocalRecvPort()));
			LOG.warn("GNSS数据解析接收服务器启动成功[监听端口：" + this.gnssComm.getLocalRecvPort() + ", 处理线程数：" + processorCount
					+ ", 读缓存大小：" + this.gnssComm.getLocalRecvBufsize() + " 字节]!");
		} else {
			LOG.info("GNSS数据解析接收服务器已经启！");
		}
	}
	
	/**
	 * 退出...
	 */
	public void shutdown(){
		if(this.acceptor != null){
			this.acceptor.dispose();
		}
		LOG.info("GnssParseResultAcceptor Exit!");
	}
}
